package com.sharding.jdbc.mybatis.algorithm;

import io.shardingsphere.core.api.algorithm.sharding.ListShardingValue;
import io.shardingsphere.core.api.algorithm.sharding.ShardingValue;
import io.shardingsphere.core.api.algorithm.sharding.complex.ComplexKeysShardingAlgorithm;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class ValueDataSourceAlgorithm implements ComplexKeysShardingAlgorithm {
    @Override
    public Collection<String> doSharding(Collection<String> datasourceNames, Collection<ShardingValue> shardingValues) {
//        System.out.println("************ datasourceNames="+datasourceNames);
//        System.out.println("************ shardingValues="+shardingValues);

        List<String> targetTableNames = new LinkedList<>();

        String[] dataSources = new String[datasourceNames.size()];
        datasourceNames.toArray(dataSources);

        ListShardingValue[] values = new ListShardingValue[shardingValues.size()];
        shardingValues.toArray(values);

        for (int i = 0; i < shardingValues.size(); i ++) {
            String name = getDatasourceName(dataSources, values[i]);
            targetTableNames.add(name);
        }

        return targetTableNames;
    }

    private String getDatasourceName(String[] datasourceNames, ListShardingValue value) {

        String logicTableName = value.getLogicTableName();
        Long id = Long.parseLong(String.valueOf(value.getValues().toArray()[0]));

        String ends = String.valueOf(id % 2);

        String dbName = null;

        for (String name : datasourceNames) {
            if (name.endsWith(ends)) {
                dbName = name;
                break;
            }
        }

        return dbName;
    }
}
